package controllers

import (
	// "database/sql"
	// "fmt"
	// "log"
	"chuanyou10/db"
	"chuanyou10/models"
	"encoding/json"
	"fmt"

	"github.com/astaxie/beego"
	// "github.com/prometheus/common/model"
)

type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

func (c *MainController) Login() {
	c.TplName = "login.html"
	// c.Data["Website"] = "登陆"
	// c.Data["Name"] = "李彬"
	// c.Data["Sn"] = "220320204010"
	// c.Data["Age"] = "20"
	// c.Data["Email"] = "astaxie@gmail.com"
	// c.TplName = "index.tpl"
}
func (c *MainController) YanzhengLogin() {
	var sn = c.GetString("sn")
	var pswd = c.GetString("pswd")
	fmt.Println("学号:", sn, "密码:", pswd)
	var currentPerson models.Classmates
	db.DB.Raw("select * from chuanyou.classmates where sn=?", sn).Scan(&currentPerson)
	// 假数据判断
	if currentPerson.Pswd == pswd {
		c.Data["json"] = currentPerson
	} else {
		c.Data["json"] = nil
	}
	c.ServeJSON()
}

func (c *MainController) Register() {
	c.TplName = "register.html"
}

func (c *MainController) Doregister() {
	var userinfo models.Classmates
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &userinfo)
	if err != nil {
		fmt.Println("接受用户信息错误:", err.Error())
		c.Data["json"] = err.Error()
		c.ServeJSON()
		return

	}
	// fmt.Println("用户学号：", userinfo.Sn)
	// db.DB.Exec("INSERT INTO `chuanyou`.`classmates` (`name`, `sn`, `sex`,`tel`) VALUES ('" + userinfo.Name +
	// 	"', '" + userinfo.Sn + "', '" + userinfo.Sex + "','" + userinfo.Tel + "')")

	// fmt.Println("用户学号:", userinfo.Sn)
	// c.Data["json"] = "注册成功"
	// c.ServeJSON()

	tx := db.DB.Create(userinfo)
	if tx.Error != nil {
		c.Data["json"] = "注册失败，原因是：" + tx.Error.Error()
		c.ServeJSON()
		return
	}
	c.Data["json"] = "注册成功"
	c.ServeJSON()
}
